const fs = require('fs');
const path = require('path');
const { parse, stringify } = require('svgson');
const svgPathBoundingBox = require('svg-path-bounding-box');

class TrimSvg {
  constructor(config) {
    this.config = config;
  }

  getPathBounds(d) {
    try {
      const bounds = svgPathBoundingBox(d);
      if (bounds && typeof bounds === 'object') {
        return {
          x: bounds.minX || 0,
          y: bounds.minY || 0,
          width: (bounds.maxX || 0) - (bounds.minX || 0),
          height: (bounds.maxY || 0) - (bounds.minY || 0),
        };
      }
      throw new Error('无效的边界值');
    } catch (err) {
      throw new Error(`无法解析 path: ${err.message}`);
    }
  }

  updateViewBox(svgJson, bounds) {
    svgJson.attributes.viewBox = `${bounds.x} ${bounds.y} ${bounds.width} ${bounds.height}`;
    return svgJson;
  }

  async process(mainWindow) {
    const { svgFile, outputDir } = this.config;
    
    // 发送开始进度
    if (mainWindow) {
      mainWindow.webContents.send('progress-update', {
        type: 'trim-svg',
        progress: 0
      });
    }
    
    // 确保输出目录存在
    if (!fs.existsSync(outputDir)) {
      fs.mkdirSync(outputDir, { recursive: true });
    }

    // 发送进度更新
    if (mainWindow) {
      mainWindow.webContents.send('progress-update', {
        type: 'trim-svg',
        progress: 50
      });
    }

    const content = fs.readFileSync(svgFile, 'utf8');
    const svgJson = await parse(content);
    const pathElements = svgJson.children.filter(el => el.name === 'path' && el.attributes.d);
    
    if (pathElements.length === 0) {
      throw new Error('未找到 <path> 元素');
    }

    // 合并所有 path 的边界
    let totalBounds = null;
    for (const el of pathElements) {
      const b = this.getPathBounds(el.attributes.d);
      if (b) {
        if (!totalBounds) {
          totalBounds = { ...b };
        } else {
          totalBounds.x = Math.min(totalBounds.x, b.x);
          totalBounds.y = Math.min(totalBounds.y, b.y);
          totalBounds.width = Math.max(totalBounds.x + totalBounds.width, b.x + b.width) - totalBounds.x;
          totalBounds.height = Math.max(totalBounds.y + totalBounds.height, b.y + b.height) - totalBounds.y;
        }
      }
    }

    if (!totalBounds) {
      throw new Error('无法计算SVG边界');
    }

    const fileName = path.basename(svgFile);
    const outputPath = path.join(outputDir, fileName);
    
    this.updateViewBox(svgJson, totalBounds);
    const output = stringify(svgJson);
    
    fs.writeFileSync(outputPath, output, 'utf8');
    
    // 发送完成进度
    if (mainWindow) {
      mainWindow.webContents.send('progress-update', {
        type: 'trim-svg',
        progress: 100
      });
    }
    
    return {
      success: true,
      message: `成功裁剪SVG: ${fileName}`,
      outputPath: outputPath
    };
  }
}

module.exports = TrimSvg;